{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Skeleton-based action recognition using TAO PoseClassificationNet\n",
    "\n",
    "Transfer learning is the process of transferring learned features from one application to another. It is a commonly used training technique where you use a model trained on one task and re-train to use it on a different task. \n",
    "\n",
    "Train Adapt Optimize (TAO) Toolkit  is a simple and easy-to-use Python based AI toolkit for taking purpose-built AI models and customizing them with users' own data.\n",
    "\n",
    "<img align=\"center\" src=\"https://d29g4g2dyqv443.cloudfront.net/sites/default/files/akamai/TAO/tlt-tao-toolkit-bring-your-own-model-diagram.png\" width=\"1080\">\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Learning Objectives\n",
    "\n",
    "In this notebook, you will learn how to leverage the simplicity and convenience of TAO to:\n",
    "\n",
    "* Train a model for skeleton-based action recognition on the [Kinetics](https://deepmind.com/research/open-source/kinetics) dataset.\n",
    "* Evaluate the trained model.\n",
    "* Run Inference on the trained model.\n",
    "* Export the trained model to an .onnx file (encrypted ONNX model) for deployment to DeepStream or TensorRT.\n",
    "* Convert the pose data from [deepstream-bodypose-3d](https://github.com/NVIDIA-AI-IOT/deepstream_reference_apps/tree/master/deepstream-bodypose-3d) to skeleton arrays for inference.\n",
    "\n",
    "At the end of this notebook, you will have generated a trained and optimized `PoseClassification` model, \n",
    "which you may deploy with this [end-to-end sample](https://github.com/NVIDIA-AI-IOT/tao-toolkit-triton-apps) with Triton.\n",
    "\n",
    "## Table of Contents\n",
    "\n",
    "This notebook shows an example usecase of PoseClassificationNet using Train Adapt Optimize (TAO) Toolkit.\n",
    "\n",
    "0. [Set up env variables and map drives](#head-0)\n",
    "1. [Installing the TAO launcher](#head-1)\n",
    "2. [Prepare dataset and pre-trained model](#head-2)\n",
    "3. [Provide training specification](#head-3)\n",
    "4. [Run TAO training](#head-4)\n",
    "5. [Evaluate trained models](#head-5)\n",
    "6. [Inferences](#head-6)\n",
    "7. [Deploy](#head-7)\n",
    "8. [Convert pose data](#head-8)\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 0. Set up env variables and map drives <a class=\"anchor\" id=\"head-0\"></a>\n",
    "\n",
    "When using the purpose-built pretrained models from NGC, please make sure to set the `$KEY` environment variable to the key as mentioned in the model overview. Failing to do so, can lead to errors when trying to load them as pretrained models.\n",
    "\n",
    "The TAO launcher uses docker containers under the hood, and **for our data and results directory to be visible to the docker, they need to be mapped**. The launcher can be configured using the config file `~/.tao_mounts.json`. Apart from the mounts, you can also configure additional options like the Environment Variables and amount of Shared Memory available to the TAO launcher. <br>\n",
    "\n",
    "`IMPORTANT NOTE:` The code below creates a sample `~/.tao_mounts.json`  file. Here, we can map directories in which we save the data, specs, results and cache. You should configure it for your specific case so these directories are correctly visible to the docker container.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# Please define this local project directory that needs to be mapped to the TAO docker session.\n",
    "%env LOCAL_PROJECT_DIR=/path/to/local/tao-experiments\n",
    "\n",
    "os.environ[\"HOST_DATA_DIR\"] = os.path.join(os.getenv(\"LOCAL_PROJECT_DIR\", os.getcwd()), \"data\", \"poseclassificationnet\")\n",
    "os.environ[\"HOST_RESULTS_DIR\"] = os.path.join(os.getenv(\"LOCAL_PROJECT_DIR\", os.getcwd()), \"poseclassificationnet\")\n",
    "\n",
    "# Set this path if you don't run the notebook from the samples directory.\n",
    "# %env NOTEBOOK_ROOT=/path/to/local/tao-experiments/pose_classification_net\n",
    "# The sample spec files are present in the same path as the downloaded samples.\n",
    "os.environ[\"HOST_SPECS_DIR\"] = os.path.join(\n",
    "    os.getenv(\"NOTEBOOK_ROOT\", os.getcwd()),\n",
    "    \"specs\"\n",
    ")\n",
    "os.environ[\"PROJECT_DIR\"]=FIXME\n",
    "\n",
    "# Set your encryption key, and use the same key for all commands\n",
    "%env KEY = nvidia_tao"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! mkdir -p $HOST_DATA_DIR\n",
    "! mkdir -p $HOST_SPECS_DIR\n",
    "! mkdir -p $HOST_RESULTS_DIR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Mapping up the local directories to the TAO docker.\n",
    "import json\n",
    "import os\n",
    "mounts_file = os.path.expanduser(\"~/.tao_mounts.json\")\n",
    "tlt_configs = {\n",
    "   \"Mounts\":[\n",
    "       # Mapping the data directory\n",
    "       {\n",
    "           \"source\": os.environ[\"LOCAL_PROJECT_DIR\"],\n",
    "           \"destination\": \"/workspace/tao-experiments\"\n",
    "       },\n",
    "       {\n",
    "           \"source\": os.environ[\"HOST_DATA_DIR\"],\n",
    "           \"destination\": \"/data\"\n",
    "       },\n",
    "       {\n",
    "           \"source\": os.environ[\"HOST_SPECS_DIR\"],\n",
    "           \"destination\": \"/specs\"\n",
    "       },\n",
    "       {\n",
    "           \"source\": os.environ[\"HOST_RESULTS_DIR\"],\n",
    "           \"destination\": \"/results\"\n",
    "       }\n",
    "   ],\n",
    "   \"DockerOptions\": {\n",
    "        \"shm_size\": \"16G\",\n",
    "        \"ulimits\": {\n",
    "            \"memlock\": -1,\n",
    "            \"stack\": 67108864\n",
    "         }\n",
    "   }\n",
    "}\n",
    "# Writing the mounts file.\n",
    "with open(mounts_file, \"w\") as mfile:\n",
    "    json.dump(tlt_configs, mfile, indent=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cat ~/.tao_mounts.json"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Installing the TAO launcher <a class=\"anchor\" id=\"head-1\"></a>\n",
    "The TAO launcher is a python package distributed as a python wheel listed in PyPI. You may install the launcher by executing the following cell.\n",
    "\n",
    "Please note that TAO Toolkit recommends users to run the TAO launcher in a virtual env with python 3.6.9. You may follow the instruction in this [page](https://virtualenvwrapper.readthedocs.io/en/latest/install.html) to set up a python virtual env using the `virtualenv` and `virtualenvwrapper` packages. Once you have setup virtualenvwrapper, please set the version of python to be used in the virtual env by using the `VIRTUALENVWRAPPER_PYTHON` variable. You may do so by running\n",
    "\n",
    "```sh\n",
    "export VIRTUALENVWRAPPER_PYTHON=/path/to/bin/python3.x\n",
    "```\n",
    "where x >= 6 and <= 8\n",
    "\n",
    "We recommend performing this step first and then launching the notebook from the virtual environment. In addition to installing TAO python package, please make sure of the following software requirements:\n",
    "* python >=3.7, <=3.10.x\n",
    "* docker-ce > 19.03.5\n",
    "* docker-API 1.40\n",
    "* nvidia-container-toolkit > 1.3.0-1\n",
    "* nvidia-container-runtime > 3.4.0-1\n",
    "* nvidia-docker2 > 2.5.0-1\n",
    "* nvidia-driver > 455+\n",
    "\n",
    "Once you have installed the pre-requisites, please log in to the docker registry nvcr.io by following the command below\n",
    "\n",
    "```sh\n",
    "docker login nvcr.io\n",
    "```\n",
    "\n",
    "You will be triggered to enter a username and password. The username is `$oauthtoken` and the password is the API key generated from `ngc.nvidia.com`. Please follow the instructions in the [NGC setup guide](https://docs.nvidia.com/ngc/ngc-overview/index.html#generating-api-key) to generate your own API key.\n",
    "\n",
    "Please note that TAO Toolkit recommends users to run the TAO launcher in a virtual env with python >=3.6.9. You may follow the instruction in this [page](https://virtualenvwrapper.readthedocs.io/en/latest/install.html) to set up a python virtual env using the virtualenv and virtualenvwrapper packages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# SKIP this step IF you have already installed the TAO launcher.\n",
    "!pip3 install nvidia-tao"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View the versions of the TAO launcher\n",
    "!tao info"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Prepare dataset and pre-trained model <a class=\"anchor\" id=\"head-2\"></a>\n",
    " We will be using the [Kinetics](https://deepmind.com/research/open-source/kinetics) dataset for the tutorial. Download the pre-processed data of Kinetics-Skeleton [here](https://drive.google.com/uc?id=1dmzCRQsFXJ18BlXj1G9sbDnsclXIdDdR) and extract them first: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# download the dataset.\n",
    "!pip3 install -U gdown\n",
    "!gdown https://drive.google.com/uc?id=1dmzCRQsFXJ18BlXj1G9sbDnsclXIdDdR -O $HOST_DATA_DIR/st-gcn-processed-data.zip"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# extract the files\n",
    "!unzip -o $HOST_DATA_DIR/st-gcn-processed-data.zip -d $HOST_DATA_DIR\n",
    "!mv $HOST_DATA_DIR/data/Kinetics/kinetics-skeleton $HOST_DATA_DIR/kinetics\n",
    "!rm -r $HOST_DATA_DIR/data\n",
    "!rm $HOST_DATA_DIR/st-gcn-processed-data.zip"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# verify\n",
    "!ls -l $HOST_DATA_DIR/kinetics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install required dependencies from the notebook.\n",
    "!pip3 install Cython==0.29.36\n",
    "!pip3 install -r $PROJECT_DIR/deps/requirements-pip.txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# select actions\n",
    "import os\n",
    "import pickle\n",
    "import numpy as np\n",
    "\n",
    "data_dir = os.path.join(os.environ[\"HOST_DATA_DIR\"], \"kinetics\")\n",
    "\n",
    "# front_raises: 134\n",
    "# pull_ups: 255\n",
    "# clean_and_jerk: 59\n",
    "# presenting_weather_forecast: 254\n",
    "# deadlifting: 88\n",
    "selected_actions = {\n",
    "    134: 0,\n",
    "    255: 1,\n",
    "    59: 2,\n",
    "    254: 3,\n",
    "    88: 4\n",
    "}\n",
    "\n",
    "def select_actions(selected_actions, data_dir, split_name):\n",
    "    \"\"\"Select a subset of actions and their corresponding labels.\n",
    "    \n",
    "    Args:\n",
    "        selected_actions (dict): Map from selected class IDs to new class IDs.\n",
    "        data_dir (str): Path to the directory of data arrays (.npy) and labels (.pkl).\n",
    "        split_name (str): Name of the split to be processed, e.g., \"train\" and \"val\".\n",
    "        \n",
    "    Returns:\n",
    "        No explicit returns\n",
    "    \"\"\"\n",
    "    data_path = os.path.join(data_dir, f\"{split_name}_data.npy\")\n",
    "    label_path = os.path.join(data_dir, f\"{split_name}_label.pkl\")\n",
    "\n",
    "    data_array = np.load(file=data_path)\n",
    "    with open(label_path, \"rb\") as label_file:\n",
    "        labels = pickle.load(label_file)\n",
    "\n",
    "    assert(len(labels) == 2)\n",
    "    assert(data_array.shape[0] == len(labels[0]))\n",
    "    assert(len(labels[0]) == len(labels[1]))\n",
    "\n",
    "    print(f\"No. total samples for {split_name}: {data_array.shape[0]}\")\n",
    "\n",
    "    selected_indices = []\n",
    "    for i in range(data_array.shape[0]):\n",
    "        if labels[1][i] in selected_actions.keys():\n",
    "            selected_indices.append(i)\n",
    "\n",
    "    data_array = data_array[selected_indices, :, :, :, :]\n",
    "    selected_sample_names = [labels[0][x] for x in selected_indices]\n",
    "    selected_labels = [selected_actions[labels[1][x]] for x in selected_indices]\n",
    "    labels = (selected_sample_names, selected_labels)\n",
    "\n",
    "    print(f\"No. selected samples for {split_name}: {data_array.shape[0]}\")\n",
    "\n",
    "    np.save(file=data_path, arr=data_array, allow_pickle=False)\n",
    "    with open(label_path, \"wb\") as label_file:\n",
    "        pickle.dump(labels, label_file, protocol=4)\n",
    "\n",
    "select_actions(selected_actions, data_dir, \"train\")\n",
    "select_actions(selected_actions, data_dir, \"val\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We also provide scripts to process the NVIDIA dataset generated by [deepstream-bodypose-3d](https://github.com/NVIDIA-AI-IOT/deepstream_reference_apps/tree/master/deepstream-bodypose-3d). The following cells for processing the NVIDIA dataset is `Optional`."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`OPTIONAL:` Download the NVIDIA dataset and extract the files."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Download the dataset\n",
    "# !pip3 install -U gdown\n",
    "# !gdown https://drive.google.com/uc?id=1GhSt53-7MlFfauEZ2YkuzOaZVNIGo_c- -O $HOST_DATA_DIR/data_3dbp_nvidia.zip"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Extract the files\n",
    "# !mkdir -p $HOST_DATA_DIR/nvidia\n",
    "# !unzip $HOST_DATA_DIR/data_3dbp_nvidia.zip -d $HOST_DATA_DIR/nvidia\n",
    "# !rm $HOST_DATA_DIR/data_3dbp_nvidia.zip"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Verify\n",
    "# !ls -l $HOST_DATA_DIR/nvidia"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`OPTIONAL:` Download the pretrained model from NGC. We will use NGC CLI to get the data and model. For more details, go to https://ngc.nvidia.com and click the SETUP on the navigation bar."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Installing NGC CLI on the local machine.\n",
    "# ## Download and install\n",
    "# import os\n",
    "# %env CLI=ngccli_cat_linux.zip\n",
    "# !mkdir -p $HOST_RESULTS_DIR/ngccli\n",
    "\n",
    "# # Remove any previously existing CLI installations\n",
    "# !rm -rf $HOST_RESULTS_DIR/ngccli/*\n",
    "# !wget \"https://ngc.nvidia.com/downloads/$CLI\" -P $HOST_RESULTS_DIR/ngccli\n",
    "# !unzip -u \"$HOST_RESULTS_DIR/ngccli/$CLI\" -d $HOST_RESULTS_DIR/ngccli/\n",
    "# !rm $HOST_RESULTS_DIR/ngccli/*.zip \n",
    "# os.environ[\"PATH\"]=\"{}/ngccli/ngc-cli:{}\".format(os.getenv(\"HOST_RESULTS_DIR\", \"\"), os.getenv(\"PATH\", \"\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !ngc registry model list nvidia/tao/poseclassificationnet:*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !mkdir -p $HOST_RESULTS_DIR/pretrained"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Pull pretrained model from NGC \n",
    "# !ngc registry model download-version \"nvidia/tao/poseclassificationnet:trainable_v1.0\" --dest $HOST_RESULTS_DIR/pretrained"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# print(\"Check that model is downloaded into dir.\")\n",
    "# !ls -l $HOST_RESULTS_DIR/pretrained/poseclassificationnet_vtrainable_v1.0"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Provide training specification <a class=\"anchor\" id=\"head-3\"></a>\n",
    "\n",
    "We provide specification files to configure the training parameters including:\n",
    "\n",
    "* model: configure the model setting\n",
    "    * model_type: type of model, ST-GCN\n",
    "    * pretrained_model_path: path for the input model\n",
    "    * input_channels: number of input channels\n",
    "    * dropout: probability to drop the hidden units\n",
    "    * graph_layout: type of graph layout, nvidia/openpose/human3.6m/ntu-rgb+d/ntu_edge/coco\n",
    "    * graph_strategy: type of graph strategy, uniform/distance/spatial\n",
    "    * edge_importance_weighting: enabling edge importance weighting\n",
    "* dataset: configure the dataset and augmentation methods\n",
    "    * train_dataset: paths for the training data and label file\n",
    "    * val_dataset: paths for the validation data and label file\n",
    "    * num_classes: number of classes\n",
    "    * label_map: map from labels to class IDs\n",
    "    * random_choose: enabling randomly choosing a portion of the input sequence\n",
    "    * random_move: enabling randomly moving the input sequence\n",
    "    * window_size: length of the output sequence\n",
    "    * batch_size: number of arrays in 1 batch\n",
    "    * num_workers: number of workers to do data loading\n",
    "* train: configure the training hyperparameters\n",
    "    * optim: configure optimizer\n",
    "    * num_epochs: number of epochs\n",
    "    * checkpoint_interval: enabling how often to store models\n",
    "    * grad_clip: enabling gradient clipping\n",
    "\n",
    "Please refer to the TAO documentation about PoseClassificationNet to get all the parameters that are configurable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "!cat $HOST_SPECS_DIR/experiment_kinetics.yaml"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Run TAO training <a class=\"anchor\" id=\"head-4\"></a>\n",
    "* Provide the sample spec file and the output directory location for models.\n",
    "* WARNING: Training will take several hours or one day to complete."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# NOTE: The following paths are set from the perspective of the TAO Docker.\n",
    "\n",
    "# The data is saved here\n",
    "%env DATA_DIR = /data\n",
    "%env SPECS_DIR = /specs\n",
    "%env RESULTS_DIR = /results"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.1 Train Kinetics model"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will train a Kinetics model from scratch."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "print(\"Train model\")\n",
    "!tao model pose_classification train \\\n",
    "                  -e $SPECS_DIR/experiment_kinetics.yaml \\\n",
    "                  results_dir=$RESULTS_DIR/kinetics \\\n",
    "                  encryption_key=$KEY"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# print(\"Train model using multiple (2) GPUs\")\n",
    "# !tao model pose_classification train \\\n",
    "#                   -e $SPECS_DIR/experiment_kinetics.yaml \\\n",
    "#                   results_dir=$RESULTS_DIR/kinetics \\\n",
    "#                   encryption_key=$KEY \\\n",
    "#                   train.gpu_ids=[0,1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Encrypted checkpoints:')\n",
    "print('---------------------')\n",
    "!ls -ltrh $HOST_RESULTS_DIR/kinetics/train"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# You can set NUM_EPOCH to the epoch corresponding to any saved checkpoint\n",
    "# %env NUM_EPOCH=029\n",
    "\n",
    "# Get the name of the checkpoint corresponding to your set epoch\n",
    "# tmp=!ls $HOST_RESULTS_DIR/kinetics/train/*.pth | grep epoch_$NUM_EPOCH\n",
    "# %env CHECKPOINT={tmp[0]}\n",
    "\n",
    "# Or get the latest checkpoint\n",
    "os.environ[\"CHECKPOINT\"] = os.path.join(os.getenv(\"HOST_RESULTS_DIR\"), \"kinetics/train/pc_model_latest.pth\")\n",
    "\n",
    "print('Rename a trained model: ')\n",
    "print('---------------------')\n",
    "!cp $CHECKPOINT $HOST_RESULTS_DIR/kinetics/train/kinetics_model.tlt\n",
    "!ls -ltrh $HOST_RESULTS_DIR/kinetics/train/kinetics_model.tlt"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `OPTIONAL` 4.2 Train NVIDIA model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# print(\"Train model from scratch\")\n",
    "# !tao model pose_classification train \\\n",
    "#                   -e $SPECS_DIR/experiment_nvidia.yaml \\\n",
    "#                   results_dir=$RESULTS_DIR/nvidia \\\n",
    "#                   encryption_key=$KEY"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# print(\"Train model from scratch using multiple (2) GPUs\")\n",
    "# !tao model pose_classification train \\\n",
    "#                   -e $SPECS_DIR/experiment_nvidia.yaml \\\n",
    "#                   results_dir=$RESULTS_DIR/nvidia \\\n",
    "#                   encryption_key=$KEY \\\n",
    "#                   train.gpu_ids=[0,1]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We provide pre-trained ST-GCN model trained on the NVIDIA dataset. With the pre-trained model, we can even get better accuracy with less epochs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# print(\"To resume training from a checkpoint, set the model.pretrained_model_path option to be the .tlt you want to resume from\")\n",
    "# print(\"remember to remove the `=` in the checkpoint's file name\")\n",
    "# !tao model pose_classification train \\\n",
    "#                   -e $SPECS_DIR/experiment_nvidia.yaml \\\n",
    "#                   results_dir=$RESULTS_DIR/nvidia \\\n",
    "#                   encryption_key=$KEY \\\n",
    "#                   model.pretrained_model_path="
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# print('Encrypted checkpoints:')\n",
    "# print('---------------------')\n",
    "# !ls -ltrh $HOST_RESULTS_DIR/nvidia/train"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# You can set NUM_EPOCH to the epoch corresponding to any saved checkpoint\n",
    "# %env NUM_EPOCH=029\n",
    "\n",
    "# Get the name of the checkpoint corresponding to your set epoch\n",
    "# tmp=!ls $HOST_RESULTS_DIR/nvidia/train/*.pth | grep epoch_$NUM_EPOCH\n",
    "# %env CHECKPOINT={tmp[0]}\n",
    "\n",
    "# Or get the latest checkpoint\n",
    "# os.environ[\"CHECKPOINT\"] = os.path.join(os.getenv(\"HOST_RESULTS_DIR\"), \"nvidia/train/pc_model_latest.pth\")\n",
    "\n",
    "# print('Rename a trained model: ')\n",
    "# print('---------------------')\n",
    "# !cp $CHECKPOINT $HOST_RESULTS_DIR/nvidia/train/nvidia_model.tlt\n",
    "# !ls -ltrh $HOST_RESULTS_DIR/nvidia/train/nvidia_model.tlt"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Evaluate trained models <a class=\"anchor\" id=\"head-5\"></a>\n",
    "Evaluate trained model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model pose_classification evaluate \\\n",
    "                    -e $SPECS_DIR/experiment_kinetics.yaml \\\n",
    "                    results_dir=$RESULTS_DIR/kinetics \\\n",
    "                    encryption_key=$KEY \\\n",
    "                    evaluate.checkpoint=$RESULTS_DIR/kinetics/train/kinetics_model.tlt \\\n",
    "                    evaluate.test_dataset.data_path=$DATA_DIR/kinetics/val_data.npy \\\n",
    "                    evaluate.test_dataset.label_path=$DATA_DIR/kinetics/val_label.pkl"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Inferences <a class=\"anchor\" id=\"head-6\"></a>\n",
    "In this section, we run the pose classification inference tool to generate inferences with the trained models and save the results under `$RESULTS_DIR`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model pose_classification inference \\\n",
    "                    -e $SPECS_DIR/experiment_kinetics.yaml \\\n",
    "                    results_dir=$RESULTS_DIR/kinetics \\\n",
    "                    encryption_key=$KEY \\\n",
    "                    inference.checkpoint=$RESULTS_DIR/kinetics/train/kinetics_model.tlt \\\n",
    "                    inference.output_file=$RESULTS_DIR/kinetics/inference/inference.txt \\\n",
    "                    inference.test_dataset.data_path=$DATA_DIR/kinetics/val_data.npy"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Deploy <a class=\"anchor\" id=\"head-7\"></a>\n",
    "Export the model to encrypted ONNX model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "!tao model pose_classification export \\\n",
    "                   -e $SPECS_DIR/experiment_kinetics.yaml \\\n",
    "                   results_dir=$RESULTS_DIR/kinetics \\\n",
    "                   encryption_key=$KEY \\\n",
    "                   export.checkpoint=$RESULTS_DIR/kinetics/train/kinetics_model.tlt \\\n",
    "                   export.onnx_file=$RESULTS_DIR/kinetics/export/kinetics_model.onnx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Exported model:')\n",
    "print('------------')\n",
    "!ls -lth $HOST_RESULTS_DIR/kinetics/export"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may continue by deploying the exported model to [Triton Inference Server](https://developer.nvidia.com/nvidia-triton-inference-server). Please refer to the [TAO Toolkit Triton Apps](https://github.com/NVIDIA-AI-IOT/tao-toolkit-triton-apps), where a sample for end-to-end inference from video is also provided. "
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## `OPTIONAL` 8. Convert pose data <a class=\"anchor\" id=\"head-8\"></a>\n",
    "Convert the JSON pose data from [deepstream-bodypose-3d](https://github.com/NVIDIA-AI-IOT/deepstream_reference_apps/tree/master/deepstream-bodypose-3d) to NumPy arrays for inference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !tao model pose_classification dataset_convert \\\n",
    "#                    -e $SPECS_DIR/experiment_nvidia.yaml \\\n",
    "#                    results_dir=$RESULTS_DIR/nvidia \\\n",
    "#                    encryption_key=$KEY \\\n",
    "#                    dataset_convert.data=/absolute/path/to/your/json/pose/data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# print('Converted pose data:')\n",
    "# print('------------')\n",
    "# !ls -lth $HOST_RESULTS_DIR/nvidia/dataset_convert"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook has come to an end."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.2 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.2"
  },
  "vscode": {
   "interpreter": {
    "hash": "706d984c9c6beac43a7cfd9240131b30df33fac60be17d555c46d6e5ebc817d6"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
